package cn.bluech.lib.utils;

import android.text.TextUtils;

/**
 * Created by Codeant on 2018/5/11.
 */

public class ByteUtils {
    private final static char[] DIGITS = {
            '0' , '1' , '2' , '3' , '4' , '5' ,
            '6' , '7' , '8' , '9' , 'A' , 'B' ,
            'C' , 'D' , 'E' , 'F'
    };

    public static String toHex(byte[] data, int offset, int len, String join) {
        StringBuilder builder = new StringBuilder();

        if(null==data)
            return "";
        if(data.length<len)
            len = data.length;

        for(;offset < len; offset++) {
            builder.append(DIGITS[(data[offset]>>4)&0x0F]);
            builder.append(DIGITS[data[offset]&0x0F]);
            // 分隔符
            if((!TextUtils.isEmpty(join))&&(offset<len-1))
                builder.append(join);
        }

        return builder.toString();
    }

    public static String toHex(byte[] data, String join) {
        if(null==data)
            return "";

        return toHex(data,0,data.length,join);
    }

    public static String toHex(byte[] data) {
        return toHex(data,null);
    }


    public static String toHex(short value){
        return String.valueOf(DIGITS[(value >> 12) & 0x0F]) +
                DIGITS[(value >> 8) & 0x0F] +
                DIGITS[(value >> 4) & 0x0F] +
                DIGITS[value & 0x0F];
    }

    public static String toHex(int value){
        return String.valueOf(DIGITS[(value >> 28) & 0x0F]) +
                DIGITS[(value >> 24) & 0x0F] +
                DIGITS[(value >> 20) & 0x0F] +
                DIGITS[(value >> 16) & 0x0F] +
                DIGITS[(value >> 12) & 0x0F] +
                DIGITS[(value >> 8) & 0x0F] +
                DIGITS[(value >> 4) & 0x0F] +
                DIGITS[value & 0x0F];
    }
}
